<?php
/**
 * ImportLogger.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/10/24- 5:09 下午
 */
namespace console\components\misc;
use Yii;
class ImportLogger
{
    /**
     * 日志路径
     * @var string
     */
    private $_logPath;

    /**
     * 文件句柄
     * @var resource|false
     */
    private $_handler;


    /**
     * ImportLogger constructor.
     * @param string $path
     */
    public function __construct(string $path)
    {
        $this->_logPath = $path.DIRECTORY_SEPARATOR.'log';
        $this->_handler = fopen($this->_logPath, 'ab');
    }

    /**
     * 添加内容
     * @param string $message
     */
    public function add(string $message): void
    {

        fwrite($this->_handler, $message."\n");
    }

    /**
     * 获取读取生成器
     * @return \Generator
     */
    public function getReadGenerator(): \Generator
    {
        fclose($this->_handler);

        $handler = fopen($this->_logPath, 'rb');

        while ($item = fgets($handler))
        {
            yield($item);
        }

        fclose($handler);
    }
}
